import { NextRequest, NextResponse } from 'next/server';
import { authMiddleware, TokenPayload } from '@/utils/auth';
import UserModel from '@/models/user';

export async function GET(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }

    const decoded = authResult as TokenPayload;
    const userId = decoded.id;

    // 获取用户信息
    const user = await UserModel.findById(userId);
    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }

    // 如果用户不是企业管理员，将其设置为企业管理员
    if (!user.is_company_admin) {
      try {
        // 更新用户为企业管理员
        const updateData = {
          is_company_admin: true,
          company: user.username + '的公司', // 默认公司名称
          company_role: '管理员'
        };

        await UserModel.updateProfile(userId, updateData);

        // 创建新企业
        const [result] = await UserModel.query<any>(
          `INSERT INTO companies (name, admin_user_id, created_at)
           VALUES (?, ?, NOW())`,
          [updateData.company, userId]
        );

        if (result && typeof result === 'object' && 'insertId' in result) {
          return NextResponse.json({
            id: result.insertId,
            name: updateData.company,
            admin_user_id: userId,
            created_at: new Date().toISOString()
          });
        }
      } catch (error) {
        console.error('创建企业信息失败:', error);
      }

      // 如果创建失败，返回空的企业信息
      return NextResponse.json({
        name: user.username + '的公司',
        admin_user_id: userId,
        created_at: new Date().toISOString()
      });
    }

    // 获取企业信息
    try {
      const [companies] = await UserModel.query<any[]>(
        `SELECT * FROM companies WHERE admin_user_id = ? OR name = ? LIMIT 1`,
        [userId, user.company]
      );

      if (!companies || (Array.isArray(companies) && companies.length === 0)) {
        // 如果没有找到企业记录，创建一个新的
        const [result] = await UserModel.query<any>(
          `INSERT INTO companies (name, admin_user_id, created_at)
           VALUES (?, ?, NOW())`,
          [user.company, userId]
        );

        // 确保 result 具有 insertId 属性
        const insertId = result && typeof result === 'object' && 'insertId' in result
          ? result.insertId
          : null;

        if (insertId) {
          const [newCompany] = await UserModel.query<any[]>(
            `SELECT * FROM companies WHERE id = ?`,
            [insertId]
          );

          if (Array.isArray(newCompany) && newCompany.length > 0) {
            return NextResponse.json(newCompany[0]);
          }
        }

        // 如果无法获取新创建的公司信息，返回基本信息
        return NextResponse.json({
          name: user.company,
          admin_user_id: userId,
          created_at: new Date().toISOString()
        });
      }

      return NextResponse.json(companies[0]);
    } catch (dbError) {
      console.error('获取企业信息失败:', dbError);
      return NextResponse.json(
        { error: '获取企业信息失败' },
        { status: 500 }
      );
    }

  } catch (error) {
    console.error('获取企业信息错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
}
